<?php

namespace App\Http\Controllers\V1;

use App\Exceptions\CouponCodeUnavailableException;
use App\Http\Resources\CouponResource;
use App\Http\Resources\MemberCouponResource;
use App\Models\Coupon;
use App\Service\CouponService;
use function foo\func;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CouponController extends Controller
{

    /**
     * 获取的我优惠券
     *
     * @param Request $request
     * @return mixed
     */
    public function memberCoupon(Request $request)
    {
        $user = $request->user();

        $coupons = $user->coupons()->with('coupon')->where(function ($query){
            if (request()->type == 1) { // 已使用
                $query->where('use_at', '<>', null);
            }
            if (request()->type == 2) { // 未使用
                $query->where('use_at', null)->where('end_time', '>', now());
            }
            if (request()->type == 3) { // 已过期
                $query->where('end_time', '<', now())->where('use_at', null);
            }
        })->paginate(10);
        return $this->success([
            'list' => MemberCouponResource::collection($coupons),
            'total' => $coupons->total(),
            'current' => $coupons->currentPage(),
        ]);
    }

    /**
     * 领取优惠券
     *
     * @param Request $request
     * @param CouponService $service
     * @return mixed
     */
    public function receiveCoupon(Request $request, CouponService $service)
    {
        $user = $request->user();

        $coupon = Coupon::findOrFail($request->coupon_id);

        try {
            $coupon->checkReceiveCoupon();
        } catch (CouponCodeUnavailableException $exception) {
            return $this->failed($exception->getMessage());
        }
        if(!$service->giveCouponToUser($coupon, $user->id)) {
            return $this->failed('您已经领取');
        }

        return $this->message('领取成功');
    }

    /**
     * 优惠券列表
     *
     * @param CouponService $service
     * @return mixed
     */
    public function getCouponList(CouponService $service) {
        return $this->success(CouponResource::collection($service->getCouponList()));
    }
}
